package com.chaoli.reggie_diy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chaoli.reggie_diy.common.R;
import com.chaoli.reggie_diy.domain.Employee;
import com.chaoli.reggie_diy.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //根据用户名进行搜索
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //对传入的用户的密码进行md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));

        //如果没有查询到用户，则返回错误信息
        if (emp == null) {
            return R.error("该用户不存在");
        }

        //如果密码不匹配，返回错误信息
        if (!password.equals(emp.getPassword())) {
            return R.error("密码不匹配");
        }

        //0为禁用状态,如果状态被锁住，返回错误信息
        if (emp.getStatus() == 0) {
            return R.error("该用户被封锁");
        }

        //登陆成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);

    }

    /**
     * 员工推出
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success("退出成功!!!");
    }

    /**
     * 新增员工
     *
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("新增员工，员工信息:{}", employee.toString());
        //设置初始密码，需要进行md5加密后在保存到数据库
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8)));

        //下面注释的代码是因为使用了mp的公共字段填充功能，所以不需要手动设置值
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        //获得当前登录用户的id
//        Long empId = (Long) request.getSession().getAttribute("employee");
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);

        employeeService.save(employee);
        return R.success("新增员工成功!!!");
    }

    /**
     * 员工信息分页查询
     *
     * @param page     当前页
     * @param pageSize 每页显示数量
     * @param name     查询的内容
     * @return Page对象
     */
    @GetMapping("/page")
    //因为是接收到的是请求参数，所以用@RequestParam
    //在name没有赋值的时候加上RequestParam注解会报错，所以不写注解，按照默认赋值规则进行赋值
    public R<Page<Employee>> page(@RequestParam(value = "page") int page, @RequestParam(value = "pageSize") int pageSize, String name) {
        log.info("page(当前页) = {} ,pageSize(每页显示数据的数量) = {} ,name = {}", page, pageSize, name);
        //分页构造器
        //page 当前页，pageSize 每页显示的条数
        Page<Employee> employeePage = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        lambdaQueryWrapper.orderByAsc(Employee::getCreateTime);
        //原地操作，对employeePage对象进行封装
        employeeService.page(employeePage, lambdaQueryWrapper);

        return R.success(employeePage);

    }

    /**
     * 根据id修改员工信息
     *
     * 这是一个通用的关于员工信息修改的方法，例如：启用、禁用、编辑
     *
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("员工信息：{}", employee.toString());
        log.info("线程id为：" + Thread.currentThread().getId());

        // 使用了mp的公共字段填充功能，所以不需要手动进行公共字段的数据填充
        //获取当前用户的id
//        Long empId = (Long) request.getSession().getAttribute("employee");
//        employee.setUpdateUser(empId);
//        employee.setUpdateTime(LocalDateTime.now());

        employeeService.updateById(employee);
        return R.success("员工信息修改成功!!");

    }

    /**
     * 根据id进行员工信息的查询并在页面上回显
     *
     * @return
     */
    @GetMapping("/{empId}")
    public R<Employee> getById(@PathVariable Long empId) {
        log.info("根据id查询员工信息进行页面上信息的回显");
        Employee employee = employeeService.getById(empId);
        if (null != employee) {
            return R.success(employee);
        }
        return R.error("没有查询到该员工的信息");
    }

}
